﻿namespace Away.Jobs.Repositories.Implements;

[ServiceInject(ServiceLifetime.Scoped)]
public class TriggerRepository : JobRepositoryBase, ITriggerRepository
{
    private readonly IMapper _mapper;
    public TriggerRepository(JobsDbContext context, IMapper mapper) : base(context)
    {
        _mapper = mapper;
    }

    public ApiResult GetTriggerPage(TriggerSearch search)
    {
        var cond = CondBuilder.New<QrtzTrigger>(true)
            .And(!string.IsNullOrWhiteSpace(search.JobGroup), o => o.JobGroup == search.JobGroup)
            .And(!string.IsNullOrWhiteSpace(search.JobName), o => o.JobName.Contains(search.JobName))
            .And(!string.IsNullOrWhiteSpace(search.TriggerName), o => o.TriggerName == search.TriggerName)
            .And(!string.IsNullOrWhiteSpace(search.TriggerGroup), o => o.TriggerGroup.Contains(search.TriggerGroup));

        var tb = Query<QrtzTrigger>()
            .Include(o => o.QrtzBlobTrigger)
            .Include(o => o.QrtzCronTrigger)
            .Include(o => o.QrtzSimpleTrigger)
            .Include(o => o.QrtzSimpropTrigger)
            .Where(cond);

        var total = tb.Count();
        var items = tb.OrderByDescending(o => o.JobName)
            .Page(search)
            .ToList()
            .Select(_mapper.Map<TriggerModel>)
            .ToList();
        return ApiResult.Page(total, items);
    }
}
